import json
import random
import string
from datetime import date

from django.db.models import F, Sum, CharField
from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.db import transaction
from django.urls import reverse

from cart.models import Cart
from store.models import Goods, Customer, StorageRecordOfGoods, StorageRecord


def index(request):
    good_of_cart = Cart.objects.filter(id_deleted=False).values("id")\
        .annotate(sum_price=Sum(F('amount')*F("good__selling_price"), output_field=CharField()))\
        .values("sum_price", "id", "amount", "good__id", "good__name", "good__specification", "good__selling_price", "good__unit", )
    organizations = Customer.objects.filter(is_customer=0)
    # result = {}
    # for organization in organizations:
    #     members = Member.objects.filter(organization=organization)
    #     result[organization.organization] = members
    return render(request, "cart.html", {"goods": good_of_cart, "organizations": organizations})


def single_pay(request):
    return None


def add(request):
    # 从仓库中拿出来放到购物车中，如果失败则回滚
    id = int(request.POST.get("id", ""))
    amount = int(request.POST.get("amount", ""))
    if not amount:
        HttpResponse("200")
    if request.method == "POST":
        with transaction.atomic():
            # 可以重写这个model自定义这个方法
            good = Goods.objects.get(id=id)
            if Cart.objects.filter(good=id, id_deleted=False).exists():
                Cart.objects.filter(good=id, id_deleted=False).update(amount=F('amount')+amount)
            else:
                Cart.objects.create(good=good, amount=amount)

            if good.quantity_in_store < amount:
                raise InterruptedError
            else:
                good.quantity_in_store = good.quantity_in_store-amount
                good.save()

    return HttpResponse("200")


def good_add(request):
    """
    往购物车中一个指定的商品数量加一
    :param request:
    :return: 1添加成功 0添加失败，仓库没货了。
    """
    if request.method == "POST":
        # good_id 是id carts_goods_id 是外键ID
        good = Goods.objects.get(id=request.POST.get('cart_goods_id'))
        if good.quantity_in_store:
            with transaction.atomic():
                good.quantity_in_store = good.quantity_in_store-1
                good.save()
                Cart.objects.filter(id=int(request.POST.get('goods_id'))).update(amount=F('amount')+1)
            return HttpResponse(1)
        else:
            return HttpResponse(0)
    return HttpResponse(0)


def good_reduce(request):
    """
      往购物车中一个指定的商品数量减一
      :param request:
      :return: 1减少加成功 0减少失败。
      """
    if request.method == "POST":
        # good_id 是id carts_goods_id 是外键ID
        good = Cart.objects.get(id=request.POST.get('goods_id'))
        if good.amount:
            with transaction.atomic():
                good.amount = good.amount-1
                good.save()
                Goods.objects.filter(id=int(request.POST.get('cart_goods_id'))).update(quantity_in_store=F('quantity_in_store') + 1)
            return HttpResponse(1)
        else:
            return HttpResponse(0)
    return HttpResponse(0)


def good_remove(request):
    if request.method == "POST":
        # good_id 是id
        good = Cart.objects.get(id=request.POST.get('goods_id'))
        with transaction.atomic():
            good.good.quantity_in_store = good.good.quantity_in_store + good.amount
            good.good.save()
            good.amount = 0
            good.id_deleted = True
            good.save()
        return HttpResponse(1)
    return HttpResponse(0)


def jiesuan(request):
    drop_item = request.GET.get("drop_item", "")
    if drop_item:
        drop_good_id = json.loads(drop_item)
        # 全没选
        if len(drop_good_id) == Cart.objects.filter(id_deleted=False).count():
            return redirect(reverse("store:index"))
        for id in drop_good_id:
            # 未选中的归还给数据库
            with transaction.atomic():
                cart = Cart.objects.get(id=id["goodsid"])
                cart.good.quantity_in_store = cart.good.quantity_in_store + cart.amount
                cart.good.save()
                cart.amount = 0
                cart.id_deleted = True
                cart.save()
    # 添加单子
    # 防止单号冲突
    number = date.today().strftime("%Y-%m-%d") + '-' + ''.join(random.choices(string.digits, k=6))
    try:
        while StorageRecord.objects.get(number=number).exists():
            number = date.today().strftime("%Y-%m-%d") + '-' + ''.join(random.choices(string.digits, k=6))
    except StorageRecord.DoesNotExist:
        pass
    goods_list = []
    with transaction.atomic():
        orgnization = Customer.objects.get(id=int(request.GET.get("hand_people")[0]))
        ticket = StorageRecord(number=number, organization=orgnization)
        ticket.total_pries = 0
        ticket.save()
        cart_goods = Cart.objects.filter(id_deleted=False)
        for i in cart_goods:
            goods_list.append(StorageRecordOfGoods(storage_record=ticket, goods=i.good, amount=i.amount,
                                                   pries=i.good.selling_price, cost=i.good.cost, total_pries=0))
        cart_goods.update(id_deleted=True)

        StorageRecordOfGoods.objects.bulk_create(goods_list)

        StorageRecordOfGoods.objects.filter(storage_record=ticket).update(total_pries=F("amount") * F("pries"))

        ticket.total_pries = StorageRecordOfGoods.objects.filter(storage_record=ticket).aggregate(sum=Sum("total_pries"))["sum"]
        ticket.save()

    return redirect(reverse("store:ticket", kwargs={"id": ticket.id}))
